<?php

namespace plugin\voice\app\admin\controller;

use support\Request;
use Webman\Medoo\Medoo as db;

class KeyController{

    public function index(Request $request){
        return raw_view('key/index');
    }

    public function insert(Request $request){
        if ($request->method() === 'POST') {
            db::insert('voice_model_keys', $request->post());
            return json([
                'code' => 0,
                'msg'  => 'ok'
            ]);
        }
        return raw_view('key/insert');
    }
    
    public function batchInsert(Request $request){
        if ($request->method() === 'POST') {
            $postData = $request->post();
            if($postData['model_id']==''){
                return json([
                    'code' => -1,
                    'msg'  => '模型不能为空'
                ]);
            }
            foreach ($postData['api_key_list'] as $key) {
                $checkKey = db::get('voice_model_keys','id',['api_key' => $key]);
                if(!$checkKey){
                    db::insert('voice_model_keys',['api_key' => $key,'model_id' => $postData['model_id']]);
                }
            }
            
            return json([
                'code' => 0,
                'msg'  => 'ok',
            ]);
        }
        return raw_view('key/batch-insert');
    }
    
    public function select(Request $request){
        $condition = [];
        foreach ($request->get() as $key => $value) {
            if($value && !in_array($key,['page','limit'])){
                $condition = array_merge($condition, [$key => $value]);
            }
        }
        $countTotal = db::count('voice_model_keys',$condition);
        $condition  = array_merge($condition, ['LIMIT' => [($request->get('page')-1)*$request->get('limit'),$request->get('limit')],'ORDER' => ['ID' => 'DESC']]);
        $keys       = db::select('voice_model_keys','*',$condition);
        foreach ($keys as &$key) {
            $key['model_name'] = db::get('voice_models','name',['id' => $key['model_id']]);
        }
        return json([
            'code'  => 0, 
            'msg'   => 'ok', 
            'count' => $countTotal,
            'data'  => $keys
        ]);
    }

    public function update(Request $request){
        if ($request->method() === 'POST') {
            $postData = $request->post();
            db::update('voice_model_keys',$postData,['id' => $postData['id']]);
            return json([
                'code' => 0,
                'msg'  => 'ok'
            ]);
        }
        return raw_view('key/update');
    }
    
    public function delete(Request $request){
        db::delete('voice_model_keys',['id' => $request->post('id')]);
        return json([
            'code' => 0,
            'msg'  => '删除成功'
        ]);
    }

}
